const moment = require('moment')
const Store = require('../../model/Store')
const async = require('async')
const request = require('request')
const Voucher = require('../../model/Voucher')
const User = require('../../model/User')
const MyVoucher = require('../../model/MyVoucher')
const Order = require('../../model/Order')


module.exports = {
    changeVoucher: async(req, res, next) => {
        try {
            if (req.body.id) {
                let voucher = await Voucher.findById(req.body.id).exec()
                voucher.store = req.body.store, // 如果没有绑定店铺，就是全局通用
                voucher.title = req.body.title,
                voucher.originalPrice=req.body.originalPrice,//原价
                voucher.discountPrice = req.body.discountPrice, //现价
                voucher.updatedAt= new Date(),
                voucher.description = req.body.description,
                voucher.buyExpireDate = req.body.buyExpireDate, // 购买过期时间
                voucher.buyStartDate = req.body.buyStartDate, // 购买开始时间
                voucher.useExpireDate = req.body.useExpireDate, //使用截止时间,
                voucher.useStartDate = req.body.useStartDate, //允许开始使用时间
                voucher.useExpireType = req.body.useExpireType , // 0为永久有效，1为按照useExpireDate和useStartDate计算, 2为购买后多少天计算
                voucher.useExpireDay = req.body.useExpireDay , // 如果useExpireType为2，需要填天数，即购买xx天后有效
                voucher.totalCount = req.body.totalCount, //总发行量
                voucher.limit = req.body.limit, // 每人领取张数限制，不填默认为1,
                voucher.status = req.body.status, //0未上线， 1上线
                voucher.images=req.body.images,
                voucher.detail= req.body.detail,
                voucher.point= req.body.point,
                voucher.productCategory = req.body.productCategory,
                voucher.thumbnail=req.body.thumbnail,
                voucher.foreignImage=req.body.foreignImage
                await voucher.save()
                res.ok('修改成功', voucher)
            } else if (!req.body.id) {
                let newVoucher = new Voucher({
                    store : req.body.store, // 如果没有绑定店铺，就是全局通用
                    title : req.body.title,
                    originalPrice:req.body.originalPrice,//原价
                    discountPrice : req.body.discountPrice, //现价
                    updatedAt: new Date(),
                    description : req.body.description,
                    buyExpireDate : req.body.buyExpireDate, // 购买过期时间
                    buyStartDate : req.body.buyStartDate, // 购买开始时间
                    useExpireDate : req.body.useExpireDate, //使用截止时间,
                    useStartDate : req.body.useStartDate, //允许开始使用时间
                    useExpireType : req.body.useExpireType , // 0为永久有效，1为按照useExpireDate和useStartDate计算, 2为购买后多少天计算
                    useExpireDay : req.body.useExpireDay , // 如果useExpireType为2，需要填天数，即购买xx天后有效
                    totalCount : req.body.totalCount, //总发行量
                    currentCount : req.body.totalCount, // 现存量 , 每次领取 数量 - 1,
                    limit : req.body.limit, // 每人领取张数限制，不填默认为1,
                    status : 0, //0未上线， 1上线
                    images:req.body.images,
                    detail: req.body.detail, 
                    point : req.body.point, //积分兑换
                    isDelete : 0,
                    productCategory:req.body.productCategory,
                    thumbnail:req.body.thumbnail,
                    foreignImage:req.body.foreignImage
                })
                await newVoucher.save()
                res.ok('创建成功', newVoucher)
            }
        } catch (e) {
            next(e)
        }
    },

    
    deleteVoucher: async(req, res, next) => {
        try {
            let voucher = await Voucher.findOne({ _id: req.body.id }).exec()
            voucher.isDelete = 1
            await voucher.save()
            res.ok('删除成功', voucher)
        } catch (e) {
            next(e)
        }
    },

    
    getVoucherList: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if (req.body.title) {
                option.title = new RegExp(req.body.title, 'i')
            }
            if (req.body.status) {
                option.status = req.body.status
            }
            if (req.body.store) {
                option.store = {$in:req.body.store}
            }
            if (req.body.productCategory) {
                option.productCategory = req.body.productCategory
            }
            let count = await Voucher.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await Voucher.find(option).skip((page - 1) * pageSize).limit(pageSize).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },

    
    voucherOnshelf: async(req, res, next) => {
        try {
            let voucher = await Voucher.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            voucher.status = 1
            await voucher.save()
            res.ok('上线成功', voucher)
        } catch (e) {
            next(e)
        }
    },

    voucherOffShelf: async(req, res, next) => {
        try {
            let voucher = await Voucher.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            voucher.status = 0
            await voucher.save()
            res.ok('下线成功', voucher)
        } catch (e) {
            next(e)
        }
    },

    getOneVoucher: async(req, res, next) => {
        try {
            let voucher = await Voucher.findOne({_id:req.body.id,isDelete:0}).populate('store').exec()
            res.ok('获取成功', voucher)
        } catch (e) {
            next(e)
        }
    },
    useVoucher: async(req, res, next) => {
        try {
            let staff = req.session.user._id
            let voucherId = req.body.voucher
            let user = await User.findOne({_id:req.body.user,isDelete:0}).exec()
            let myVoucher = await MyVoucher.findOne({openid:user.openid,voucher:voucherId}).exec()
            if(myVoucher.status == 1){
                let otherMyVoucher = await MyVoucher.findOne({openid:user.openid,voucher:voucherId,status:0}).exec()
                if(otherMyVoucher == null){
                    res.send({code:201,msg:"抵用券已被使用"})
                }else{
                    otherMyVoucher.status = 1
                    await otherMyVoucher.save()
                    res.ok('使用成功', otherMyVoucher)
                }
            }else if(myVoucher.status == 0){
                myVoucher.status = 1
                await myVoucher.save()
                res.ok('使用成功', myVoucher)
            }
        } catch (e) {
            next(e)
        }
    },

    writeOffVoucher: async(req, res, next) => {
        try {
            let nowDate = new Date()
            let userVoucher = await MyVoucher.findOne({order:req.body.order,isDelete:0,status:0}).exec()
            let voucher = await Voucher.findOne({_id:userVoucher.voucher}).exec()
            if(userVoucher==null){
                res.send({code:201,msg:"未查询到可使用的兑换券"})
            }else if(voucher.useExpireType ==1){
                console.log(nowDate,voucher.useStartDate,voucher.useExpireDate)
                if(nowDate < voucher.useStartDate){
                    res.send({ code: 201, msg: "未到开始使用日期" })
                }else if(nowDate > voucher.useExpireDate){
                    res.send({ code: 201, msg: "已超过使用时间" })
                }else{
                    userVoucher.status = 1
                    userVoucher.useDate = new Date()
                    await userVoucher.save()
                    let order = await Order.findOne({_id:userVoucher.order,isDelete:0}).exec()
                    order.useDate = new Date()
                    await order.save()
                    res.ok('核销成功')
                }
            }else if(voucher.useExpireType ==2){
                if(nowDate>moment(myVoucher.createdAt).add(myVoucher.useExpireDay, 'days')){
                    res.send({ code: 201, msg: "已超过使用时间" })
                }else{
                    userVoucher.status = 1
                    userVoucher.useDate = new Date()
                    await userVoucher.save()
                    let order = await Order.findOne({_id:userVoucher.order,isDelete:0}).exec()
                    order.useDate = new Date()
                    await order.save()
                    res.ok('核销成功')
                }
            }else{
                userVoucher.status = 1
                userVoucher.useDate = new Date()
                await userVoucher.save()
                let order = await Order.findOne({_id:userVoucher.order,isDelete:0}).exec()
                order.useDate = new Date()
                await order.save()
                res.ok('核销成功')
            }
        } catch (e) {
            next(e)
        }
    },
    
};